package com.tianxin.workbao.workBao.Activity;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.adapter.SelectCarAdapter;
import com.tianxin.workbao.workBao.bean.CarFinance;
import com.tianxin.workbao.workBao.bean.CarInformation;
import com.tianxin.workbao.workBao.bean.Fueldiary;
import com.tianxin.workbao.workBao.bean.OilPrice;
import com.tianxin.workbao.workBao.bean.Storage;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.dataProvide.CarFinanceProvide;
import com.tianxin.workbao.workBao.dataProvide.CarProvide;
import com.tianxin.workbao.workBao.dataProvide.OilPriceProvide;
import com.tianxin.workbao.workBao.dataProvide.StorageProvide;
import com.tianxin.workbao.workBao.holder.SelectCarHolder;
import com.tianxin.workbao.workBao.listener.MyPopupWindowListener;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.SPUtils;
import com.tianxin.workbao.workBao.utils.common.StringUtils;
import com.tianxin.workbao.workBao.utils.common.TimeUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by hacker on 2017/6/22.
 */

public class AddOilOptionActivity extends BaseActivity implements View.OnClickListener, UpdateListViewListener, MyPopupWindowListener {

    private TextView carInformationTV;
    private TextView addTimeTV;
    private TextView addUserTV;
    private TextView totalMoneyTV;
    private EditText oilMassET;
    private EditText searchContentET;
    private TextView unitPriceTV;
    private TextView numberTV;
    private TextView gasStationStorageTV;
    private TextView residual_moneyTV;
    private FloatingActionButton saveFab;
    private int isBackFinish = 0;
    private Fueldiary mFueldiary;
    private float currentStorage = 0;
    private float currentOilPrice = 0;

    private Storage mStorage;
    private OilPrice mOilPrice;
    private CarInformation mCarInformation;
    private CarFinance mCarFinance;
    private StorageProvide storageProvide;
    private OilPriceProvide oilPriceProvide;
    private CarProvide carProvide;
    private List<CarInformation> carInformationList;

    private CarFinanceProvide carFinanceProvide;
    private Float volume;
    private Float money;
    private Float residualMoney;
    private PopupWindow popupWindow;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_oil_option);
        super.initStatusBar(true);
        initData();

        initView();

        initEvent();

        bindView();
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }

    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle(getResources().getString(R.string.add_oil));
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(AppCompatResources.getDrawable(this, R.drawable.ic_action_back_24dp));
        saveFab = (FloatingActionButton) findViewById(R.id.save_fab);

        carInformationTV = (TextView) findViewById(R.id.car_information);
        addTimeTV = (TextView) findViewById(R.id.add_Time);
        addUserTV = (TextView) findViewById(R.id.add_user);
        totalMoneyTV = (TextView) findViewById(R.id.total_money);
        oilMassET = (EditText) findViewById(R.id.oil_mass);
        searchContentET = (EditText) findViewById(R.id.et_search_content);
        unitPriceTV = (TextView) findViewById(R.id.unit_price);
        gasStationStorageTV = (TextView) findViewById(R.id.gas_station_storage);
        numberTV = (TextView) findViewById(R.id.number);
        residual_moneyTV = (TextView) findViewById(R.id.residual_money);
    }

    @Override
    public void initData() {
        mFueldiary = new Fueldiary();
        getCurrentOilPrice();
        getCurrentStorage();
    }


    @Override
    public void initEvent() {
        //navigationIcon event
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AddOilOptionActivity.this.finish();
            }
        });
        saveFab.setOnClickListener(this);
        searchContentET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String queryString = editable.toString();
                if (!StringUtils.isNumber(queryString)) {
                    showMessage("输入错误");
                    carInformationTV.setText("");
                    carInformationTV.setFocusable(true);
                    return;
                }
                if (StringUtils.isHasChineseChar(queryString)) {
                    //get car information by plateNumber
                    if (StringUtils.isPlateNumber(queryString) == true) {
                        //not do nothing
                    } else {
                        showMessage("车牌号错误");
                        carInformationTV.setText("");
                        carInformationTV.setFocusable(true);
                    }
                } else {
                    if (queryString.length() >= 3 && queryString.length() <= 5) {
                        //get car by plateNumber like query string
                        if(queryString.startsWith("800")){
                            return;
                        }else {
                            showPopupWindow(queryString);
                        }
                    } else if (queryString.length() > 5 && queryString.length() == 8) {
                        if (StringUtils.isNumber(queryString) == true) {
                            //get cars by gas card number
                            getCarProvide().getcarBycpunumber(queryString);
                            // get car finance residual money in the interface
                        } else {
                            showMessage("输入错误");
                            carInformationTV.setText("");
                            carInformationTV.setFocusable(true);
                        }
                    } else if (queryString.length() > 8) {
                        showMessage("输入错误");
                        carInformationTV.setText("");
                        carInformationTV.setFocusable(true);
                    }
                }
            }
        });
        oilMassET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String volumeString = editable.toString();
                if (volumeString.length() == 0) {
                    return;
                }
                try {
                    volume = Float.valueOf(volumeString);
                    if (volume > currentStorage) {
                        showMessage("加油升数不能大于油库库存");
                        oilMassET.setText("");
                        return;
                    }
                    money = Float.valueOf(Constant.mDecimalFormat.format(currentOilPrice * volume));
                    totalMoneyTV.setText(money + "");

                    residualMoney = Float.valueOf(residual_moneyTV.getText().toString());
                    if (money > residualMoney) {
                        showMessage("余额不足");
                        oilMassET.setText("");
                        return;
                    }
                } catch (NumberFormatException e) {
                    showMessage("加油升数输入错误");
                    oilMassET.setText("");
                    e.printStackTrace();
                    return;
                }
            }
        });
    }

    /**
     * show the select car popup window
     */
    private void showSelectCarPopupWindow() {
         popupWindow = new PopupWindow();
        SelectCarAdapter selectCarAdapter = new SelectCarAdapter(carInformationList, this, this);
        SelectCarHolder selectCarHolder = new SelectCarHolder(this, this, selectCarAdapter);
        popupWindow.setContentView(selectCarHolder.getContentView());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setHeight(300);
        popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.write)));
        popupWindow.setAnimationStyle(R.style.my_popup_animation_style);
        popupWindow.showAtLocation(mToolbar, Gravity.TOP, 0, 0);
    }

    /**
     * indistinct get car  like queryString
     *
     * @param queryString
     */
    private void showPopupWindow(String queryString) {
        getCarProvide().getCarinformationsLikeQueryString(queryString);
    }

    @Override
    public void bindView() {
        numberTV.setText(BeansUtil.getNumber(Constant.FUELDIARY_HEADER));
        addUserTV.setText(SPUtils.getPrefString(Constant.CURRENT_USER_NAME, "null"));
        addTimeTV.setText(TimeUtils.parseDateTime(new Date()));
        carInformationTV.setText("null");
        unitPriceTV.setText("");
        gasStationStorageTV.setText("");
        bindStorageData();
        bindPriceData();
    }

    /**
     * set current  gas station stock
     */
    private void bindStorageData() {
        if (currentStorage > 0) {
            gasStationStorageTV.setText(currentStorage + "");
        } else {
            gasStationStorageTV.setText("0.0");
        }

    }

    /**
     * set current oil price
     */
    private void bindPriceData() {
        if (currentOilPrice > 0) {
            unitPriceTV.setText(currentOilPrice + "");
        } else {
            unitPriceTV.setText("0.0");
        }

    }

    /**
     * set car information
     */
    private void bindcarData() {
        if (mCarInformation != null) {
            unitPriceTV.setText(currentOilPrice + "");
            carInformationTV.setText(mCarInformation.getPlatenumbers()
                    + "  " + mCarInformation.getOwner() + "  "
                    + BaseActivity.formatPhoneNumber(mCarInformation.getConnectphone()));
        } else {
            carInformationTV.setTextColor(getResources().getColor(R.color.red_btn_bg_pressed_color));
            carInformationTV.setText("车辆信息不正确");
        }

    }

    /**
     * set car finance residual money
     */
    private void bindCarFinanceData() {
        if (mCarInformation != null) {
            residual_moneyTV.setText(mCarFinance.getResidualmoney() + "");
        } else {
            residual_moneyTV.setTextColor(getResources().getColor(R.color.red_btn_bg_pressed_color));
            residual_moneyTV.setText("车辆信息不正确");
        }

    }

    @Override
    public void onBackPressed() {
        //alert
        super.onBackPressed();
    }

    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        switch (viewId) {
            case R.id.save_fab:
                saveAddOilRecord();
                break;
        }
    }

    /**
     * add oil
     */
    private void saveAddOilRecord() {
        if (mCarInformation == null) {
            showMessage("车辆信息不存在，不可以加油");
            return;
        }
        if (volume > 0 && money > 0) {
            Fueldiary fueldiary = new Fueldiary();
            fueldiary.setNumber(numberTV.getText().toString());
            try {
                fueldiary.setAdduserid((int) SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0));
                fueldiary.setAddusername(SPUtils.getPrefString(Constant.CURRENT_USER_NAME, "no"));
            } catch (Exception e) {
                // user no login
                e.printStackTrace();
            }
            fueldiary.setAddtime(new Date());
            fueldiary.setUnitprice(currentOilPrice);
            fueldiary.setStatus(Byte.valueOf("0"));
            fueldiary.setCarid((int) mCarInformation.getId());
            fueldiary.setPlatenumbers(mCarInformation.getPlatenumbers());
            fueldiary.setTotalmoney(money);
            fueldiary.setOilmass(volume);
            fueldiary.setIsis(1);
            fueldiary.setType(1);
            getOilPriceProvide().saveFueldiary(fueldiary);

        } else {
            showMessage("加油升数或者份额有错，不可以加油");
        }
    }

    @Override
    public void showMessage(String msg) {
        if (msg == "ok") {
            this.finish();
        } else if (msg.contains("failure")) {
            Toast.makeText(this, "加油失败！\n " + msg.substring(msg.indexOf("failure") + 1, msg.length()), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void showProgress() {
        getSweetAlertDialog(this).showDialog("",1200);
    }

    @Override
    public void hideProgress() {
        getSweetAlertDialog(this).dismiss();
    }

    @Override
    public void onRefreshData(Object result) {
        if (result instanceof List) {
            if (((List) result).size() > 0) {
                if (((List) result).get(0) instanceof CarInformation) {
                    carInformationList = (List<CarInformation>) result;
                    showSelectCarPopupWindow();
                }
            }
        } else if (result instanceof Storage) {
            mStorage = (Storage) result;
            currentStorage = mStorage.getVolume();
            bindStorageData();
        } else if (result instanceof OilPrice) {
            mOilPrice = (OilPrice) result;
            currentOilPrice = mOilPrice.getUnitprice();
            bindPriceData();
        } else if (result instanceof CarInformation) {
            mCarInformation = (CarInformation) result;
            // get car finance residual money
            getResidualMoney();
            bindcarData();
        } else if (result instanceof CarFinance) {
            mCarFinance = (CarFinance) result;
            bindCarFinanceData();
        } else {
            showMessage("response other information");
        }
    }


    @Override
    public void onLoadMoreData(Object result) {

    }

    public void getCurrentStorage() {
        if (storageProvide == null) {
            storageProvide = new StorageProvide(AddOilOptionActivity.this, this);
        }
        storageProvide.getData();
    }

    public void getCurrentOilPrice() {
        if (oilPriceProvide == null) {
            oilPriceProvide = new OilPriceProvide(AddOilOptionActivity.this, this);
        }
        oilPriceProvide.getData(1);
    }

    public CarProvide getCarProvide() {
        if (carProvide == null) {
            carProvide = new CarProvide(this, this);
        }
        return carProvide;
    }

    public OilPriceProvide getOilPriceProvide() {
        if (oilPriceProvide == null) {
            oilPriceProvide = new OilPriceProvide(this, this);
        }
        return oilPriceProvide;
    }

    public void getResidualMoney() {
        if (mCarInformation == null) {
            showMessage("车辆信息异常");
            return;
        }
        getCarFinanceProvide().getCarfinance(mCarInformation.getPlatenumbers());
    }


    public CarFinanceProvide getCarFinanceProvide() {
        if (carFinanceProvide == null) {
            carFinanceProvide = new CarFinanceProvide(this, this);
        }
        return carFinanceProvide;
    }

    @Override
    public void OnMyClick(Integer selectType, Integer id, String information) {
        switch (selectType) {
            case Constant.SELECT_TYPE_CAR:
                if(popupWindow!=null){
                    popupWindow.dismiss();
                }
                getCarProvide().getcarByPlateNumber(information);
                break;
        }
    }
}
